//
//  WxChatMgrLogin.m
//  WxSdk
//
//  Created by fusuwei on 14-9-9.
//  Copyright (c) 2014年 网信金融集团. All rights reserved.
//

#import "IWxChatMgrLogin.h"
#include "PublicMacros.h"

#import "UcfgroupXMPPManger.h"
#import "ChatLoginUserMgr.h"

@class ChatLoginUser;



@implementation IWxChatMgrLogin


static IWxChatMgrLogin *sharedInstance = nil;

+ (IWxChatMgrLogin *)sharedInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil )
        {
            sharedInstance = [[self alloc] init];
        }
    }
    
    return sharedInstance;
}

-(id)init
{
	self=[super init];
	if(self)
    {
 
    }
	return self;
}


/*!
 @method
 @brief      注册一个监听对象到监听列表中
 @discussion 把监听对象添加到监听列表中准备接收相应的事件
 @param      delegate 需要注册的监听对象
 @param      appId  应用Id
 @param      secret 应用密码
 @result     成功：@"OK"    失败：**参数为空
 */
- (NSString *)registDelegate:(id<EWxChatMgrLoginDelegate>)delegate appId:(NSString *)appId secret:(NSString *)secret
{
    WXLog(@"registDelegate");
    if (delegate == nil) {
        return @"delegate参数为空";
    }
    if (appId == nil || [appId isEqualToString:@""]) {
        return @"appId参数为空";
    }
    if (secret == nil || [secret isEqualToString:@""]) {
        return @"secret参数为空";
    }
    [UcfgroupXMPPManger sharedInstance].xmppLogRegDelegate = delegate;
    
    return @"OK";
}


/*!
 @method
 @brief      登录成功后上传设备devicetoken到聊天服务器
 @discussion 异步方法
 @param      deviceToken 设备Token串
 @result     是否上传成功
 */
- (BOOL)uploadDeviceToken:(NSData *)deviceToken
{
    //NSString *devicetoken = [pToken base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    const char* data = [deviceToken bytes];
    NSMutableString *stringPushDeviceToken = [NSMutableString string];
    
    for (int i = 0; i < [deviceToken length]; i++) {
        //[stringPushDeviceToken appendFormat:@"%02.2hhX", data[i]];
        [stringPushDeviceToken appendFormat:@"%02.2hhx", data[i]];
    }
    
    WXLog(@"uploadDeviceToken: deviceToken= %@",stringPushDeviceToken);
    UcfgroupXMPPManger* delelgate = [UcfgroupXMPPManger sharedInstance];
    delelgate.deviceToken = stringPushDeviceToken;
    
    if (deviceToken == nil) {
        [delelgate.xmppLogRegDelegate uploadDeviceTokenRspState:register_Fail];
    }
    
    return YES;
}


/*!
 @method
 @brief      从监听列表中移除一个监听对象
 @discussion 把监听对象从监听列表中移除,取消接收相应的事件
 @param      delegate 需要移除的监听对象
 @result
 */
- (void)unregistDelegate:(id<EWxChatMgrLoginDelegate>)delegate
{
    WXLog(@"unregistDelegate");
    [UcfgroupXMPPManger sharedInstance].xmppLogRegDelegate = nil;
}


/*!
 @method
 @brief 在聊天服务器上创建账号
 @discussion
 @param userid 用户名id
 @param password 密码
 @result registerNewAccountRspState:username:password:
 */
- (void)registerNewAccount:(NSString *)userid password:(NSString *)password
{
    WXLog(@"registerNewAccount: userid= %@ ,password= %@",userid,password);
    
    UcfgroupXMPPManger* delegateUcf = [UcfgroupXMPPManger sharedInstance];
    
    if (delegateUcf.xmppLogRegDelegate && [delegateUcf.xmppLogRegDelegate respondsToSelector:@selector(registerNewAccountRspState:username:password:)])
    {
        if (userid == nil || [userid isEqualToString:@""]) {
            [delegateUcf.xmppLogRegDelegate registerNewAccountRspState:register_userIdNull username:userid password:password];
            return;
        }
        if (password == nil || [password isEqualToString:@""]) {
            [delegateUcf.xmppLogRegDelegate registerNewAccountRspState:register_passwordNull username:userid password:password];
            return;
        }
    }

    NSString *jidNameValid = [self convertToJid:userid];
    
    delegateUcf.isReg = YES;
    delegateUcf.logRegWxUserObject.UserId = jidNameValid;
    delegateUcf.logRegWxUserObject.UserPassword = password;
    
    [delegateUcf connect];
    
    [[UcfgroupXMPPManger sharedInstance] addXmppRecordReqId:@"registerNewAccount" type:@"registerNewAccount" paraMsg:nil];
    return;
}


/*!
 @method
 @brief 异步方法, 使用用户名密码登录聊天服务器
 @discussion 在登陆过程中 回调会被触发
 @param userId 用户名Id
 @param password 密码
 @result
 */
- (void)loginWithUserId:(NSString *)userId password:(NSString *)password
{
    WXLog(@"loginWithUserId: userid= %@ ,password= %@",userId,password);
    
    NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
    NSString *curUserId = [self convertToJid:userId];
    if (![curUserId isEqualToString:myJID]) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:@"0" forKey:@"GroupVer"];
        [defaults setObject:@"0" forKey:@"RosterVer"];
        [defaults synchronize];
    }
    
    UcfgroupXMPPManger* delegateUcf = [UcfgroupXMPPManger sharedInstance];
    
    if (delegateUcf.xmppLogRegDelegate && [delegateUcf.xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
    {
        WXLog(@"loginWithUserId: 启动正常登录");
        if (userId == nil || [userId isEqualToString:@""]) {
            NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                       userId, @"userid", password, @"password",
                                       @"用户Id为空", @"describe",
                                       nil];
            [delegateUcf.xmppLogRegDelegate loginWithUserIdRspState:login_Fail loginInfo:loginInfo];
            return;
        }
        if (password == nil || [password isEqualToString:@""]) {
            NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                       userId, @"userid", password, @"password",
                                       @"用户密码为空", @"describe",
                                       nil];
            [delegateUcf.xmppLogRegDelegate loginWithUserIdRspState:login_Fail loginInfo:loginInfo];
            return;
        }
    }
    NSString *jidNameValid = [self convertToJid:userId];
    
    
    delegateUcf.isReg = NO;
    delegateUcf.logRegWxUserObject.UserId = jidNameValid;
    delegateUcf.logRegWxUserObject.UserPassword = password;
    
    BOOL ret = [delegateUcf connect];
    WXLog(@"loginWithUserId:begin connect ret= %d",ret);
    if (ret) {
//        [delegateUcf.xmppLogRegDelegate loginWithUserIdRspState:login_OK loginInfo:nil];
    }
    
    [delegateUcf addXmppRecordReqId:@"loginWithUserId" type:@"loginWithUserId" paraMsg:nil];
}


/*!
 @method
 @brief      异步方法, 使用用户名密码登录聊天服务器
 @discussion
 @param      userId 用户名Id
 @param      password 密码
 @param      completion 回调
 @param      aQueue 回调时的线程
 @result
 */
typedef void (^completionBlock)(NSDictionary *loginInfo, EWxLoginRegState state);
- (void)asyncLoginWithUserId:(NSString *)userId
                      password:(NSString *)password
                    completion:(void (^)(NSDictionary *loginInfo, EWxLoginRegState state))completion
                       onQueue:(dispatch_queue_t)aQueue
{
    if (userId == nil || [userId isEqualToString:@""]) {
        NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                   userId, @"userid", password, @"password",
                                   @"连接服务器错误", @"describe",
                                   nil];
        completion(loginInfo, login_Fail);
         return;
    }
    if (userId == nil || [userId isEqualToString:@""]) {
        NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                   userId, @"userid", password, @"password",
                                   @"连接服务器错误", @"describe",
                                   nil];
        completion(loginInfo, login_Fail);
        return;
    }
    
    NSString *jidNameValid = [self convertToJid:userId];
    
 //   __block BOOL cancel = NO;
    //开始执行这个方法
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        UcfgroupXMPPManger* delelgate = [UcfgroupXMPPManger sharedInstance];
        delelgate.xmppLogRegDelegate = nil;
        delelgate.completion = ^(NSDictionary *loginInfo, EWxLoginRegState state)
        {
            NSLog(@"Vince 22222");
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(loginInfo,state);
            });
        };

        
        delelgate.logRegWxUserObject.UserId = jidNameValid;
        delelgate.logRegWxUserObject.UserPassword = password;
        
        [delelgate connect];
        
        NSLog(@"Vince Starting222");
        
        [delelgate addXmppRecordReqId:@"loginWithUserId" type:@"loginWithUserId" paraMsg:nil];
    });
    
    NSLog(@"Vince Starting");
}

/*!
 @method
 @brief      同步方法, 获取是否已经登录
 @result     返回BOOL    YES 成功； NO 失败；
 */
- (BOOL)isLoginSuccess
{
    UcfgroupXMPPManger* delelgate = [UcfgroupXMPPManger sharedInstance];
    BOOL islogin = [delelgate isLogSuccess];
    return  islogin;
}


/*!
 @method
 @brief      异步方法, 注销当前登录用户
 @discussion 在注销过程中, 回调会被触发
 @result
 */
- (void)loginoff
{
    //---vince@2014-10-22
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:@"0" forKey:@"GroupVer"];
//    [defaults setObject:@"0" forKey:@"RosterVer"];
//    [defaults synchronize];
    
    WXLog(@"loginoff");
    UcfgroupXMPPManger* delelgate = [UcfgroupXMPPManger sharedInstance];
    
    if (![delelgate isLogSuccess])
    {
        if (delelgate.xmppLogRegDelegate && [delelgate.xmppLogRegDelegate respondsToSelector:@selector(loginoffRspState:reason:)])
        {
            [delelgate.xmppLogRegDelegate loginoffRspState:NO reason:@"未登录！"];
        }
        return;
    }
    
    delelgate.apiEntranceType = @"loginoff";
    [delelgate disconnect];
    
    [delelgate addXmppRecordReqId:@"loginoff" type:@"loginoff" paraMsg:nil];
}


#pragma mark-------------------------通用处理方法-----------------------------
- (NSString *)convertToJid:(NSString *)jidName
{
    //WXLog(@"convertToJid: jidName= %@",jidName);
    NSString *jidNameValid = nil;
    if (jidName != nil)
    {
        jidNameValid = [NSString stringWithString:jidName];
        NSRange range = [jidNameValid rangeOfString:kXMPPmyDomain];
        if (range.length >0)//包含
        {
        }
        else //不包含
        {
            jidNameValid = [NSString stringWithFormat:@"%@%@",jidName,kXMPPmyDomain];
        }
    }
    else
    {
        WXLog(@"convertToJid: jidName=NULL");
    }
    return jidNameValid;
}


@end
